package com.yuan.common.mail;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

public class SendMail {

	private static final Logger logger = Logger.getLogger(SendMail.class);

	private String host; // smtp主机名
	private String from; // 发送方邮件地址
	private String pwd; // 发送方邮件密码
	private String fromDisplay;
	private String smtpAuth;

	public void sendEmail(String to, String subject, String content) {
		try {
			Properties props = new Properties();
			props.put("mail.smtp.auth", smtpAuth);
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.user", from);
			props.put("mail.smtp.password", pwd);

			Session sendMailSession;

			sendMailSession = Session.getInstance(props, new Authenticator() {
				public PasswordAuthentication getPasswordAuthentication() // 邮件安全认证。
				{
					return new PasswordAuthentication(from, pwd);
				}
			});

			Message newMessage = new MimeMessage(sendMailSession);
			newMessage.setFrom(new InternetAddress(from, fromDisplay));
			newMessage.setRecipient(Message.RecipientType.TO,
					new InternetAddress(to));
			newMessage.setSubject(subject);
			newMessage.setSentDate(new Date());
			newMessage.setContent(content, "text/html;charset=UTF-8");
			Transport transport = sendMailSession.getTransport("smtp");

			Transport.send(newMessage);

			logger.error("发送至:" + to + ",主题:'" + subject + "'成功");
		} catch (Exception ex) {
			logger.error("发送至:" + to + ",主题:'" + subject + "'失败", ex);
		}
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getFromDisplay() {
		return fromDisplay;
	}

	public void setFromDisplay(String fromDisplay) {
		this.fromDisplay = fromDisplay;
	}

	public String getSmtpAuth() {
		return smtpAuth;
	}

	public void setSmtpAuth(String smtpAuth) {
		this.smtpAuth = smtpAuth;
	}

}
